﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

using K.ClientOfMVC.Models;
using K.ClientOfMVC;
using K.Contract;
using K.EnterpriseLibary.Common;
using K.EnterpriseLibary.Entity;
using K.Service; //非WCF使用
using K.EnterpriseLibary.Cache;
namespace K.ClientOfMVC.Controllers
{

    [HandleError]
    public class AccountController : BaseController
    {
        public IUserService userService { get; set; }
        public AccountModel accountModel = new AccountModel();
        public string loginCode = Public.GetXMLValue("loginCode"); //读取是否开启了注册码验证
        public string isRegMobile = Public.GetXMLValue("isRegMobile"); //读取是否开启了手机注册
        public double cookieExpires = Convert.ToDouble(Public.GetXMLValue("cookieexpires"));


        protected override void Initialize(RequestContext requestContext)
        {
            if (userService == null) { userService = new UserService(); }
            base.Initialize(requestContext);
        }
        public AccountController()
            : base()
        {
            //定义本Controller下的页面公共信息
            mainModel.appInfo.SiteTitle = "用户注册";
            ViewData["MainModel"] = mainModel;
        }
        
        /// <summary>
        /// 注册画面
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            #region 是否允许注册
            string RegSwitch = Public.GetXMLValue("OpenReg"); //读取是否开放注册
            string errSTR = string.Empty; //定义错误变量
            
            //string uid = GetString("uid"); //读取当前登录ID？ 怀疑是隐藏的
            
            if (RegSwitch != "1")
            {
                if (RegSwitch == "0") //注册已关闭
                {
                    errSTR += "注册已经关闭，请与管理员联系！";
                }
                //此处删除邀请注册的判断
            }
            #endregion

            #region 界面元素
            accountModel.birthdayYear = MvcPublic.GetBirthdayYear();
            accountModel.birthdayMonth = MvcPublic.GetBirthdayMonth();
            accountModel.birthdayDay = MvcPublic.GetBirthdayDay();
            #endregion

            #region 开关设置

            //真实姓名
            string isRealName = Public.GetXMLValue("isRealName");
            if (isRealName == "1")
            {
                accountModel.isRealName = 1;
            }
  
            //验证码
            if (loginCode == "1")
            {
                accountModel.isVCode = 1;
            }
            if (!string.IsNullOrEmpty(errSTR))
            {
                accountModel.close = errSTR;
            }
            //此处删除显示手机作为用户名的字符
            #endregion
  
            return View(accountModel);
        }

        /// <summary>
        /// 注册结果画面
        /// </summary>
        /// <returns></returns>
        public ActionResult Result()
        {
            return View();
        }

        
        
        /// <summary>
        /// 注册处理
        /// </summary>
        /// <param name="username"></param>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="confimpassword"></param>
        /// <param name="truename"></param>
        /// <param name="inviteid"></param>
        /// <param name="replayEmail"></param>
        /// <param name="provinceid"></param>
        /// <param name="city"></param>
        /// <param name="sex"></param>
        /// <param name="vcode"></param>
        /// <param name="birthdayYear"></param>
        /// <param name="birthdayMonth"></param>
        /// <param name="birthdayDay"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Register(string username,string email,string password,
            string confimpassword,string truename,int inviteid,string replayEmail,
            int provinceid, int city, int sex, string vcode, string birthdayYear,
            string birthdayMonth, string birthdayDay)
        {
            bool isSuccess = false;

            #region 合法性判断
            if (string.IsNullOrEmpty(truename))
            {
                truename = username;
            }
            string errSTR = string.Empty;

            if (string.IsNullOrEmpty(username)) { errSTR += "用户名 &nbsp; "; }
            if (string.IsNullOrEmpty(email)) { errSTR += "电子邮件 &nbsp; "; }
            if (string.IsNullOrEmpty(password)) { errSTR += "密码 &nbsp; "; }
            if (string.IsNullOrEmpty(confimpassword))
            {
                errSTR += "密码不正确 &nbsp; ";
            }
            else
            {
                if (confimpassword != password)
                {
                    errSTR += "两次密码不一致 &nbsp; ";
                }
            }
            string errSTR1 = string.Empty;
            if (!Input.isEmail(email)) { errSTR1 += "电子邮件格式不正确！ "; }
            if (string.IsNullOrEmpty(truename)) { errSTR += "真实姓名 &nbsp; "; }

            if (string.IsNullOrEmpty(birthdayYear) || string.IsNullOrEmpty(birthdayMonth) || string.IsNullOrEmpty(birthdayDay)) { errSTR += "生日 &nbsp; "; }
            if (city == 0) { errSTR += "目前你居住地 &nbsp; "; }
            if (loginCode == "1")
            {
                //判断验证码是否正确
                
                if (System.Web.HttpContext.Current.Session["KFrameCheckCode"] == null) //验证码为空
                {
                    errSTR += "验证码不正确 &nbsp; ";
                }
                else
                {
                    if (vcode != System.Web.HttpContext.Current.Session["KFrameCheckCode"].ToString())
                    {
                        errSTR += "验证码不正确 &nbsp; ";
                    }
                }
            }
            #endregion 

            #region 注册用户
            if (!string.IsNullOrEmpty(errSTR) || !string.IsNullOrEmpty(errSTR1))
            {
                if (!string.IsNullOrEmpty(errSTR))
                {
                    //显示错误
                    accountModel.errors = errSTR;
                }
                else
                {
                    //显示错误
                    accountModel.errors = errSTR1;
                }
            }
            else
            {
                //检查用户名
                if (userService.CheckUserExsit(username,1))
                {
                    if (!string.IsNullOrEmpty(errSTR))
                    {
                        accountModel.errors = "用户名(" + username + ")已经存在！请重新选择一个用户名";
                    }
                }
                else
                {
                    if (userService.CheckUserExsit(email, 0))
                    {
                        accountModel.errors = "电子邮件(" + email + ")已经存在！请重新选择一个电子邮件"; 
                    }
                    else
                    {
                        UserInfo ui = new UserInfo();
                        ui.UserName = username;
                        ui.Email = email;
                        ui.Password = Input.MD5(password, false);
                        ui.ProvinceID = provinceid;
                        ui.City = city;
                        ui.TrueName = truename;
                        ui.InviterID = inviteid;
                        ui.Sex = Convert.ToByte(sex);
                        UserBaseInfo basi = new UserBaseInfo();
                        string bday = birthdayYear + "-" + birthdayMonth + "-" + birthdayDay;
                        basi.Birthday = Convert.ToDateTime(bday);
                        int uid = 0;
                        string uName = string.Empty;
                        EnumRegister ret = userService.Register(ui, basi, out uid);
                        switch (ret)
                        {
                            case EnumRegister.Succeed:
                                //这里删除邀请注册收相互加为好友的代码
                                //将用户信息放入Cookie中
                                Cookies.SetCookie(cookieExpires, "USER_COOKIE_UID", uid, "USER_COOKIE_USERNAME", userService.GetUserInfo(uid).UserName, "USER_COOKIE_PASSWORD", Input.MD5(password, false));
                                //这里删除插入默认好友的代码
                                //转到完成画面
                                isSuccess = true;
                                break;
                            default:
                                errSTR = "系统错误,请稍后再试";
                                break;
                        }
                        if (!string.IsNullOrEmpty(errSTR))
                        {
                            accountModel.errors = errSTR;
                        }
                    }
                }
            }
            #endregion

            if (isSuccess)
                return RedirectToAction("Result");
            return View(accountModel);
        }
    }

}
